<template>
  <div class="system-overview">
    <!-- 页面标题 -->
    <div class="page-header">
      <div class="header-left">
        <h2 class="page-title">
          <i class="el-icon-monitor"></i>
          系统概览
        </h2>
        <span class="page-subtitle">系统运行状态和统计信息</span>
      </div>
      <div class="header-actions">
        <el-button 
          icon="el-icon-refresh" 
          @click="refreshData"
          :loading="refreshing"
          size="medium"
        >
          刷新数据
        </el-button>
      </div>
    </div>

    <!-- 统计卡片 -->
    <div class="stats-section">
      <el-row :gutter="20">
        <el-col :xs="24" :sm="12" :md="6" :lg="6">
          <el-card class="stat-card user-card" shadow="hover">
            <div class="stat-content">
              <div class="stat-icon">
                <i class="el-icon-user"></i>
              </div>
              <div class="stat-info">
                <div class="stat-number">{{ stats.userCount }}</div>
                <div class="stat-label">用户总数</div>
                <div class="stat-change" :class="stats.userChange >= 0 ? 'positive' : 'negative'">
                  <i :class="stats.userChange >= 0 ? 'el-icon-top' : 'el-icon-bottom'"></i>
                  {{ Math.abs(stats.userChange) }}%
                </div>
              </div>
            </div>
          </el-card>
        </el-col>
        <el-col :xs="24" :sm="12" :md="6" :lg="6">
          <el-card class="stat-card role-card" shadow="hover">
            <div class="stat-content">
              <div class="stat-icon">
                <i class="el-icon-s-custom"></i>
              </div>
              <div class="stat-info">
                <div class="stat-number">{{ stats.roleCount }}</div>
                <div class="stat-label">角色总数</div>
                <div class="stat-change" :class="stats.roleChange >= 0 ? 'positive' : 'negative'">
                  <i :class="stats.roleChange >= 0 ? 'el-icon-top' : 'el-icon-bottom'"></i>
                  {{ Math.abs(stats.roleChange) }}%
                </div>
              </div>
            </div>
          </el-card>
        </el-col>
        <el-col :xs="24" :sm="12" :md="6" :lg="6">
          <el-card class="stat-card permission-card" shadow="hover">
            <div class="stat-content">
              <div class="stat-icon">
                <i class="el-icon-key"></i>
              </div>
              <div class="stat-info">
                <div class="stat-number">{{ stats.permissionCount }}</div>
                <div class="stat-label">权限总数</div>
                <div class="stat-change" :class="stats.permissionChange >= 0 ? 'positive' : 'negative'">
                  <i :class="stats.permissionChange >= 0 ? 'el-icon-top' : 'el-icon-bottom'"></i>
                  {{ Math.abs(stats.permissionChange) }}%
                </div>
              </div>
            </div>
          </el-card>
        </el-col>
        <el-col :xs="24" :sm="12" :md="6" :lg="6">
          <el-card class="stat-card process-card" shadow="hover">
            <div class="stat-content">
              <div class="stat-icon">
                <i class="el-icon-document"></i>
              </div>
              <div class="stat-info">
                <div class="stat-number">{{ stats.processCount }}</div>
                <div class="stat-label">流程总数</div>
                <div class="stat-change" :class="stats.processChange >= 0 ? 'positive' : 'negative'">
                  <i :class="stats.processChange >= 0 ? 'el-icon-top' : 'el-icon-bottom'"></i>
                  {{ Math.abs(stats.processChange) }}%
                </div>
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>

    <!-- 图表区域 -->
    <div class="charts-section">
      <el-row :gutter="20">
        <el-col :xs="24" :sm="24" :md="12" :lg="12">
          <el-card class="chart-card" shadow="never">
            <div slot="header" class="chart-header">
              <span class="chart-title">用户活跃度</span>
              <el-button-group size="mini">
                <el-button 
                  :type="activePeriod === '7d' ? 'primary' : ''" 
                  @click="changeActivePeriod('7d')"
                >
                  7天
                </el-button>
                <el-button 
                  :type="activePeriod === '30d' ? 'primary' : ''" 
                  @click="changeActivePeriod('30d')"
                >
                  30天
                </el-button>
                <el-button 
                  :type="activePeriod === '90d' ? 'primary' : ''" 
                  @click="changeActivePeriod('90d')"
                >
                  90天
                </el-button>
              </el-button-group>
            </div>
            <div class="chart-container">
              <div ref="userActiveChart" class="chart"></div>
            </div>
          </el-card>
        </el-col>
        <el-col :xs="24" :sm="24" :md="12" :lg="12">
          <el-card class="chart-card" shadow="never">
            <div slot="header" class="chart-header">
              <span class="chart-title">权限分布</span>
            </div>
            <div class="chart-container">
              <div ref="permissionChart" class="chart"></div>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>

    <!-- 最近活动 -->
    <div class="activity-section">
      <el-row :gutter="20">
        <el-col :xs="24" :sm="24" :md="12" :lg="12">
          <el-card class="activity-card" shadow="never">
            <div slot="header" class="activity-header">
              <span class="activity-title">最近用户</span>
              <el-button type="text" @click="viewAllUsers">查看全部</el-button>
            </div>
            <div class="activity-list">
              <div 
                v-for="user in recentUsers" 
                :key="user.id" 
                class="activity-item"
              >
                <div class="activity-avatar">
                  <el-avatar :size="40" :src="user.avatar">
                    {{ user.name.charAt(0) }}
                  </el-avatar>
                </div>
                <div class="activity-content">
                  <div class="activity-name">{{ user.name }}</div>
                  <div class="activity-desc">{{ user.department }} · {{ user.position }}</div>
                  <div class="activity-time">{{ formatTime(user.createTime) }}</div>
                </div>
                <div class="activity-status">
                  <el-tag :type="user.status === 1 ? 'success' : 'danger'" size="mini">
                    {{ user.status === 1 ? '启用' : '禁用' }}
                  </el-tag>
                </div>
              </div>
            </div>
          </el-card>
        </el-col>
        <el-col :xs="24" :sm="24" :md="12" :lg="12">
          <el-card class="activity-card" shadow="never">
            <div slot="header" class="activity-header">
              <span class="activity-title">系统日志</span>
              <el-button type="text" @click="viewAllLogs">查看全部</el-button>
            </div>
            <div class="activity-list">
              <div 
                v-for="log in systemLogs" 
                :key="log.id" 
                class="activity-item"
              >
                <div class="activity-icon">
                  <i :class="getLogIcon(log.level)"></i>
                </div>
                <div class="activity-content">
                  <div class="activity-name">{{ log.message }}</div>
                  <div class="activity-desc">{{ log.module }} · {{ log.operation }}</div>
                  <div class="activity-time">{{ formatTime(log.createTime) }}</div>
                </div>
                <div class="activity-status">
                  <el-tag :type="getLogLevelColor(log.level)" size="mini">
                    {{ log.level }}
                  </el-tag>
                </div>
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>

    <!-- 快速操作 -->
    <div class="quick-actions-section">
      <el-card class="quick-actions-card" shadow="never">
        <div slot="header" class="quick-actions-header">
          <span class="quick-actions-title">快速操作</span>
        </div>
        <div class="quick-actions-grid">
          <div 
            v-for="action in quickActions" 
            :key="action.key"
            class="quick-action-item"
            @click="handleQuickAction(action)"
          >
            <div class="quick-action-icon">
              <i :class="action.icon"></i>
            </div>
            <div class="quick-action-label">{{ action.label }}</div>
          </div>
        </div>
      </el-card>
    </div>
  </div>
</template>

<script>
import { permissionMixin } from '@/utils/permission'

export default {
  name: 'SystemOverview',
  mixins: [permissionMixin],
  data() {
    return {
      refreshing: false,
      activePeriod: '7d',
      stats: {
        userCount: 0,
        roleCount: 0,
        permissionCount: 0,
        processCount: 0,
        userChange: 0,
        roleChange: 0,
        permissionChange: 0,
        processChange: 0
      },
      recentUsers: [],
      systemLogs: [],
      quickActions: [
        {
          key: 'addUser',
          label: '新增用户',
          icon: 'el-icon-user',
          permission: 'system:user:add'
        },
        {
          key: 'addRole',
          label: '新增角色',
          icon: 'el-icon-s-custom',
          permission: 'system:role:add'
        },
        {
          key: 'addPermission',
          label: '新增权限',
          icon: 'el-icon-key',
          permission: 'system:permission:add'
        },
        {
          key: 'createProcess',
          label: '创建流程',
          icon: 'el-icon-document',
          permission: 'process:create'
        },
        {
          key: 'systemSettings',
          label: '系统设置',
          icon: 'el-icon-setting',
          permission: 'system:settings'
        },
        {
          key: 'dataBackup',
          label: '数据备份',
          icon: 'el-icon-download',
          permission: 'system:backup'
        }
      ]
    }
  },
  mounted() {
    this.loadData()
    this.initCharts()
  },
  methods: {
    // 加载数据
    async loadData() {
      this.refreshing = true
      try {
        await Promise.all([
          this.loadStats(),
          this.loadRecentUsers(),
          this.loadSystemLogs()
        ])
      } catch (error) {
        this.$message.error('加载数据失败')
      } finally {
        this.refreshing = false
      }
    },

    // 加载统计数据
    async loadStats() {
      // 模拟数据，实际应该调用API
      this.stats = {
        userCount: 156,
        roleCount: 12,
        permissionCount: 89,
        processCount: 23,
        userChange: 12.5,
        roleChange: 0,
        permissionChange: 8.3,
        processChange: 15.2
      }
    },

    // 加载最近用户
    async loadRecentUsers() {
      // 模拟数据，实际应该调用API
      this.recentUsers = [
        {
          id: 1,
          name: '张三',
          department: '技术部',
          position: '前端工程师',
          status: 1,
          createTime: new Date(Date.now() - 2 * 60 * 60 * 1000)
        },
        {
          id: 2,
          name: '李四',
          department: '产品部',
          position: '产品经理',
          status: 1,
          createTime: new Date(Date.now() - 4 * 60 * 60 * 1000)
        },
        {
          id: 3,
          name: '王五',
          department: '运营部',
          position: '运营专员',
          status: 0,
          createTime: new Date(Date.now() - 6 * 60 * 60 * 1000)
        }
      ]
    },

    // 加载系统日志
    async loadSystemLogs() {
      // 模拟数据，实际应该调用API
      this.systemLogs = [
        {
          id: 1,
          message: '用户登录成功',
          module: '认证模块',
          operation: '用户登录',
          level: 'INFO',
          createTime: new Date(Date.now() - 10 * 60 * 1000)
        },
        {
          id: 2,
          message: '权限分配完成',
          module: '权限模块',
          operation: '权限分配',
          level: 'INFO',
          createTime: new Date(Date.now() - 30 * 60 * 1000)
        },
        {
          id: 3,
          message: '数据库连接异常',
          module: '数据库模块',
          operation: '连接检查',
          level: 'ERROR',
          createTime: new Date(Date.now() - 60 * 60 * 1000)
        }
      ]
    },

    // 初始化图表
    initCharts() {
      this.$nextTick(() => {
        this.initUserActiveChart()
        this.initPermissionChart()
      })
    },

    // 初始化用户活跃度图表
    initUserActiveChart() {
      // 这里应该使用 ECharts 或其他图表库
      // 由于没有引入图表库，这里只是占位
      const chartElement = this.$refs.userActiveChart
      if (chartElement) {
        chartElement.innerHTML = '<div style="display: flex; align-items: center; justify-content: center; height: 200px; color: #999;">图表功能需要引入 ECharts 库</div>'
      }
    },

    // 初始化权限分布图表
    initPermissionChart() {
      // 这里应该使用 ECharts 或其他图表库
      const chartElement = this.$refs.permissionChart
      if (chartElement) {
        chartElement.innerHTML = '<div style="display: flex; align-items: center; justify-content: center; height: 200px; color: #999;">图表功能需要引入 ECharts 库</div>'
      }
    },

    // 改变活跃度周期
    changeActivePeriod(period) {
      this.activePeriod = period
      this.initUserActiveChart()
    },

    // 格式化时间
    formatTime(time) {
      const now = new Date()
      const diff = now - new Date(time)
      const minutes = Math.floor(diff / (1000 * 60))
      const hours = Math.floor(diff / (1000 * 60 * 60))
      const days = Math.floor(diff / (1000 * 60 * 60 * 24))

      if (minutes < 60) {
        return `${minutes}分钟前`
      } else if (hours < 24) {
        return `${hours}小时前`
      } else {
        return `${days}天前`
      }
    },

    // 获取日志图标
    getLogIcon(level) {
      const iconMap = {
        INFO: 'el-icon-info',
        WARN: 'el-icon-warning',
        ERROR: 'el-icon-error',
        DEBUG: 'el-icon-question'
      }
      return iconMap[level] || 'el-icon-info'
    },

    // 获取日志级别颜色
    getLogLevelColor(level) {
      const colorMap = {
        INFO: 'info',
        WARN: 'warning',
        ERROR: 'danger',
        DEBUG: 'success'
      }
      return colorMap[level] || 'info'
    },

    // 查看所有用户
    viewAllUsers() {
      this.$router.push('/system/user-management')
    },

    // 查看所有日志
    viewAllLogs() {
      this.$message.info('系统日志功能开发中...')
    },

    // 刷新数据
    refreshData() {
      this.loadData()
    },

    // 处理快速操作
    handleQuickAction(action) {
      if (!this.hasPermission(action.permission)) {
        this.$message.warning('权限不足')
        return
      }

      switch (action.key) {
        case 'addUser':
          this.$router.push('/system/user-management')
          break
        case 'addRole':
          this.$router.push('/system/role-management')
          break
        case 'addPermission':
          this.$router.push('/system/permission-management')
          break
        case 'createProcess':
          this.$router.push('/process/process-form')
          break
        case 'systemSettings':
          this.$message.info('系统设置功能开发中...')
          break
        case 'dataBackup':
          this.$message.info('数据备份功能开发中...')
          break
        default:
          this.$message.info('功能开发中...')
      }
    }
  }
}
</script>

<style scoped>
.system-overview {
  padding: 20px;
  background-color: #f5f5f5;
  min-height: 100vh;
}

/* 页面标题区域 */
.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding: 20px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border-radius: 8px;
  color: white;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.header-left {
  display: flex;
  flex-direction: column;
}

.page-title {
  margin: 0;
  font-size: 24px;
  font-weight: 600;
  display: flex;
  align-items: center;
  gap: 8px;
}

.page-subtitle {
  font-size: 14px;
  opacity: 0.9;
  margin-top: 4px;
}

.header-actions {
  display: flex;
  gap: 12px;
}

.header-actions .el-button {
  background: rgba(255, 255, 255, 0.2);
  border: 1px solid rgba(255, 255, 255, 0.3);
  color: white;
  backdrop-filter: blur(10px);
}

.header-actions .el-button:hover {
  background: rgba(255, 255, 255, 0.3);
  border-color: rgba(255, 255, 255, 0.5);
}

/* 统计卡片 */
.stats-section {
  margin-bottom: 20px;
}

.stat-card {
  border-radius: 8px;
  transition: all 0.3s ease;
  cursor: pointer;
}

.stat-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 8px 25px rgba(0, 0, 0, 0.15);
}

.stat-content {
  display: flex;
  align-items: center;
  padding: 8px 0;
}

.stat-icon {
  width: 60px;
  height: 60px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 16px;
  font-size: 24px;
  color: white;
}

.user-card .stat-icon {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
}

.role-card .stat-icon {
  background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
}

.permission-card .stat-icon {
  background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
}

.process-card .stat-icon {
  background: linear-gradient(135deg, #43e97b 0%, #38f9d7 100%);
}

.stat-info {
  flex: 1;
}

.stat-number {
  font-size: 28px;
  font-weight: 700;
  color: #303133;
  line-height: 1;
  margin-bottom: 4px;
}

.stat-label {
  font-size: 14px;
  color: #909399;
  margin-bottom: 4px;
}

.stat-change {
  font-size: 12px;
  display: flex;
  align-items: center;
  gap: 2px;
}

.stat-change.positive {
  color: #67c23a;
}

.stat-change.negative {
  color: #f56c6c;
}

/* 图表区域 */
.charts-section {
  margin-bottom: 20px;
}

.chart-card {
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.chart-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.chart-title {
  font-size: 16px;
  font-weight: 600;
  color: #303133;
}

.chart-container {
  height: 200px;
}

.chart {
  width: 100%;
  height: 100%;
}

/* 活动区域 */
.activity-section {
  margin-bottom: 20px;
}

.activity-card {
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.activity-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.activity-title {
  font-size: 16px;
  font-weight: 600;
  color: #303133;
}

.activity-list {
  max-height: 300px;
  overflow-y: auto;
}

.activity-item {
  display: flex;
  align-items: center;
  padding: 12px 0;
  border-bottom: 1px solid #f0f0f0;
}

.activity-item:last-child {
  border-bottom: none;
}

.activity-avatar {
  margin-right: 12px;
}

.activity-icon {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  background: #f5f5f5;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 12px;
  font-size: 16px;
  color: #606266;
}

.activity-content {
  flex: 1;
}

.activity-name {
  font-size: 14px;
  font-weight: 500;
  color: #303133;
  margin-bottom: 2px;
}

.activity-desc {
  font-size: 12px;
  color: #909399;
  margin-bottom: 2px;
}

.activity-time {
  font-size: 12px;
  color: #c0c4cc;
}

.activity-status {
  margin-left: 12px;
}

/* 快速操作 */
.quick-actions-section {
  margin-bottom: 20px;
}

.quick-actions-card {
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.quick-actions-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.quick-actions-title {
  font-size: 16px;
  font-weight: 600;
  color: #303133;
}

.quick-actions-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(120px, 1fr));
  gap: 16px;
}

.quick-action-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 20px;
  border-radius: 8px;
  background: #fafafa;
  cursor: pointer;
  transition: all 0.3s ease;
}

.quick-action-item:hover {
  background: #f0f0f0;
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.quick-action-icon {
  width: 48px;
  height: 48px;
  border-radius: 50%;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  display: flex;
  align-items: center;
  justify-content: center;
  margin-bottom: 8px;
  font-size: 20px;
  color: white;
}

.quick-action-label {
  font-size: 14px;
  color: #606266;
  text-align: center;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .system-overview {
    padding: 10px;
  }
  
  .page-header {
    flex-direction: column;
    gap: 16px;
    text-align: center;
  }
  
  .header-actions {
    flex-wrap: wrap;
    justify-content: center;
  }
  
  .stat-content {
    flex-direction: column;
    text-align: center;
  }
  
  .stat-icon {
    margin-right: 0;
    margin-bottom: 8px;
  }
  
  .chart-header {
    flex-direction: column;
    gap: 8px;
    align-items: flex-start;
  }
  
  .activity-header {
    flex-direction: column;
    gap: 8px;
    align-items: flex-start;
  }
  
  .activity-item {
    flex-direction: column;
    align-items: flex-start;
    gap: 8px;
  }
  
  .activity-status {
    margin-left: 0;
    align-self: flex-end;
  }
  
  .quick-actions-grid {
    grid-template-columns: repeat(auto-fit, minmax(100px, 1fr));
    gap: 12px;
  }
}

/* 滚动条优化 */
.activity-list::-webkit-scrollbar {
  width: 6px;
}

.activity-list::-webkit-scrollbar-track {
  background: #f1f1f1;
  border-radius: 3px;
}

.activity-list::-webkit-scrollbar-thumb {
  background: #c1c1c1;
  border-radius: 3px;
}

.activity-list::-webkit-scrollbar-thumb:hover {
  background: #a8a8a8;
}
</style>
